package pl.edu.romanow.util

import net.liftweb.http.{SessionVar, S}
import net.liftweb.http.js.{JsCmd, JsCmds}
import net.liftweb.common._

/**
 * Created by IntelliJ IDEA.
 * User: jar
 * Date: 25.03.12
 * Time: 11:38
 * To change this template use File | Settings | File Templates.
 */

object PopupUtil {

  def openInPopup(url: String, afterRefresh: Box[JsCmd] = Empty, title: String = "") = {

    (afterRefresh match {
      case Full(js) => doOnPopupClose(js)
      case _ => JsCmds.Noop
    }) & JsCmds.Run("window.open('" + url
      + "','" + S.?(title)
      + "', 'toolbar=1,resizable=0');")
  }

  object AfterRefreshDo extends SessionVar[Box[String]](Empty)

  val popupRefreshRedirectUrl = "/util/popupRefresh"


  val afterPopupCloseFunctionName = "afterPopupCloseFunctionName"
  val newScriptTagId = "newScriptTagId";

  def doOnPopupClose(js: JsCmd): JsCmd = {

    AfterRefreshDo(Full("""if(window.opener){window.opener.""" + afterPopupCloseFunctionName + "()};"))

    JsCmds.Run("createEmptyScript('%s');".format(newScriptTagId)) &
      JsCmds.Replace(newScriptTagId, JsCmds.Script(JsCmds.Function(afterPopupCloseFunctionName, Nil, js)));
  }

}
